package com.tamplus.cs.bean;

import java.io.Serializable;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Locale;

import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletRequest;

import com.tamplus.cs.constant.Constant;
import com.tamplus.cs.constant.MessageConstant;
import com.tamplus.cs.helper.MessageHelper;

public class LoginBean extends BaseBean implements Serializable {
	private static final long serialVersionUID = 1L;
	
	private String user;
	private String password;

	public LoginBean() {}

	public String login() {
		try {
			System.out.println("User : "+user);
			System.out.println("Pwd : "+password);
			
			//TODO check login from web service
			try{
				FacesContext context = FacesContext.getCurrentInstance();
				String endPoint = MessageHelper.getLocaleString(context.getApplication().getMessageBundle(), MessageConstant.END_POINT_LOGIN, new Object[]{user, password}, Locale.US);
				//String endPoint = "http://172.18.32.1/eai_enu/start.swe?SWEExtSource=WebService&SWEExtCmd=Execute&UserName="+user+"&Password="+password;
				URL url = new URL(endPoint);
				HttpURLConnection conn = (HttpURLConnection)url.openConnection();
				//conn.connect();
				int status = conn.getResponseCode();
				if(status == HttpURLConnection.HTTP_OK || status == 400){
					ExternalContext external = FacesContext.getCurrentInstance().getExternalContext();
					HttpServletRequest request = (HttpServletRequest) external.getRequest();
					request.getSession().setAttribute(Constant.USERNAME, user);
					request.getSession().setAttribute(Constant.PASSWORD, password);
				} else{
					throw new Exception("Login Failed !");
				}
				//System.out.println("ResponseCode : " + status + " #" + HttpURLConnection.HTTP_OK);
				//BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
				//String line;
				//if((line = in.readLine()) != null){
				//	System.out.println(line);
				//}
			} catch(Exception e){
				throw new Exception(e);
			}
		} catch (Exception e) {
			e.printStackTrace();
			displayErrorMessage(MessageConstant.LOGIN_FAILED, new String[] { user });
			return "back";
		}
		return FWD_SUCCESS;
	}
	
	public String getUser() {
		return user;
	}
	public void setUser(String user) {
		this.user = user;
	}

	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
}
